package labrom.usage.server;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.UUID;

import labrom.usage.shared.Udi;

/**
 * Parses the POST request body used to record Usage Data Items.
 * @author Romain Laboisse
 *
 */
public class UdiPayload extends ArrayList<Udi> {
	
	/**
	 * Can read up to 1000 items.
	 */
	public static final int MAX_ITEMS = 1000;
	
	private static final long serialVersionUID = 1L;
	

	public static UdiPayload parse(InputStream in) throws IOException {
		ReadableByteChannel ch = Channels.newChannel(in);
		ByteBuffer buffer = ByteBuffer.allocate(16 * MAX_ITEMS);
		while(ch.read(buffer) >= 0) {
			if(!buffer.hasRemaining())
				break;
		}
		buffer.flip();
		UdiPayload udis = new UdiPayload();
		while(buffer.hasRemaining()) {
			Udi u = new Udi();
			u.setTimestamp(buffer.getLong());
			u.setTypeId(buffer.getLong());
			udis.add(u);
		}
		return udis;
	}
	
	/**
	 * Sets the client app version and instance GUID to all parsed Usage Data Items
	 * @param guid
	 */
	public void setAppVersionAndClientGuid(int appVersion, UUID guid) {
		for(Udi i : this) {
			i.setAppVersion(appVersion);
			i.setGuidLsb(guid.getLeastSignificantBits());
			i.setGuidMsb(guid.getMostSignificantBits());
		}
	}
	
	
	
}
